package com.hevs.samplewebapp.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;

import com.google.appengine.api.datastore.Key;
import com.hevs.samplewebapp.server.entities.User;
import com.hevs.samplewebapp.server.json.ObjectMapperFactory;
import com.hevs.samplewebapp.server.service.UserService;
import com.hevs.samplewebapp.shared.security.Token;

/**
 * RESTful servlet to retrieve informations from the medical datas.
 * @author Arnaud Durand
 * @date 13.03.2012
 */
public class AuthenticationServlet extends HttpServlet {

	
	private static final long serialVersionUID = 3429920868316912361L;

	/**
	 * Business logic service containing the DAO of the users
	 */
	public static UserService userService; { userService = new UserService(); };

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		User user;
		HttpSession session = req.getSession(false);
		try {
			user = userService.getUser((Key)session.getAttribute("userKey"));
		} catch (Exception e) {
			System.out.println("catch userDAO.getUser");
			resp.sendError(403);
			return;
		}

		Token tok = new Token();
		tok.setCredentialLevel(user.getCredentialLevel());
		
		tok.setKey(session.getId());

		resp.setContentType("application/json");
		PrintWriter writer = resp.getWriter();

		ObjectMapper mapper = ObjectMapperFactory.get();
		writer.write(mapper.writeValueAsString(tok));

		writer.flush();
	}
	
	
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doDelete(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		HttpSession session = req.getSession(false);
		try {
			session.removeAttribute("userKey");
			session.invalidate();

		} catch (Exception e) {
			resp.sendError(403);
			return;
		}
	}
	

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
			// ObjectMapper mapper = new ObjectMapper(); // can reuse, share
			// globall
			BufferedReader reader = req.getReader();
			StringBuilder sb = new StringBuilder();
			String line = reader.readLine();
			while (line != null) {
				sb.append(line + "\n");
				line = reader.readLine();
			}
			reader.close();
			System.out.println(sb.toString());

			ObjectMapper mapper = ObjectMapperFactory.get();
			
			User auth ;
			try{
			auth = mapper.readValue(sb.toString(),
					User.class);
			} catch (Exception e) {
				resp.sendError(400);
				return;
			}
			User user = userService.getUserByLogin(auth.getLogin());

			System.out.println(auth.getLogin());

			
			// throw Error 400
			if (user == null || !user.getPassword().equals(auth.getPassword())) {	
				resp.sendError(403);
				return;
			}
			HttpSession session = req.getSession(true);
			session.setAttribute("userKey", user.getKey());

			Token tok = new Token();
			tok.setCredentialLevel(user.getCredentialLevel());
		
			tok.setKey(session.getId());

			resp.setContentType("application/json");
			PrintWriter writer = resp.getWriter();
			writer.write(mapper.writeValueAsString(tok));

			writer.flush();

	}


}
